Page({
  data: {
    socketTask: null,
    messages: [],
    date: new Date().toLocaleString(),
    inputMessage: '',
    userId: '',
    targetUserId: '',
    avatar: '',
  },
  onLoad(options) {
    this.setData({
      targetUserId: options.targetUserId
    });
    wx.setNavigationBarTitle({
      title: this.data.targetUserId
    });
    this.connectWebSocket();
    this.getRedisMessages();

    // 添加定时器，每0.1秒刷新一次页面
    this.refreshTimer = setInterval(() => {
      this.getRedisMessages(false); // 不滚动页面
    }, 200); // 100毫秒 = 0.1秒
  },
  onShow() {
    this.getLoginMessage();
  },
  onUnload() {
    // 页面卸载时清除定时器
    clearInterval(this.refreshTimer);
  },
  getRedisMessages(scroll = true) {
    wx.request({
      url: 'http://localhost:8080/api/messages',
      method: 'GET',
      success: (res) => {
        const parsedMessages = res.data.map(item => JSON.parse(item));
        this.setData({
          messages: parsedMessages
        });
        if (scroll) {
          // 确保滚动到最新消息
          wx.pageScrollTo({
            scrollTop: 9999, // 滚动到页面底部
            duration: 300
          });
        }
      },
      fail: (err) => {
        console.error('获取消息失败：', err);
      }
    });
  },
  getLoginMessage() {
    const loginUser = wx.getStorageSync('userInfo');
    this.setData({
      userId: loginUser.userName,
      avatar: loginUser.avatar,
    });
  },
  connectWebSocket() {
    console.log('正在连接 WebSocket...');
    const socketTask = wx.connectSocket({
      url: 'ws://localhost:8080/chat?userId=' + this.data.userId,
    });

    socketTask.onOpen(() => {
      console.log('WebSocket 连接成功');
    });

    socketTask.onMessage((message) => {
      console.log('收到消息：', message.data);
      try {
        const parsedMessage = JSON.parse(message.data);
        this.setData({
          messages: [...this.data.messages, parsedMessage]
        });
        wx.nextTick(() => {
          // 确保数据更新完成后再进行下一步操作
          console.log('消息列表已更新');
          // 确保滚动到最新消息
          wx.pageScrollTo({
            scrollTop: 9999, // 滚动到页面底部
            duration: 300
          });
        });
      } catch (e) {
        console.error('解析消息失败：', e);
      }
    });

    socketTask.onError((error) => {
      console.error('WebSocket 连接错误：', error);
    });

    socketTask.onClose(() => {
      console.log('WebSocket 连接关闭');
    });

    this.setData({
      socketTask
    });
  },
  sendMessage() {
    if (this.data.socketTask && this.data.inputMessage) {
      const message = {
        from: this.data.userId,
        to: this.data.targetUserId,
        content: this.data.inputMessage,
        date: this.data.date,
        avatar: this.data.avatar
      };
      this.data.socketTask.send({
        data: JSON.stringify(message),
        success: () => {
          console.log('消息发送成功');
          this.setData({
            content: '' // 清空输入框
          });
          this.getRedisMessages(); // 发送消息成功后更新消息列表并滚动页面
          wx.pageScrollTo({
            scrollTop: 9999, // 滚动到页面底部
            duration: 300
          });
        }
      });
    }
  },
  handleInputChange(e) {
    this.setData({
      inputMessage: e.detail.value
    });
  },
});